package com.itheima.tliasmanagementspringboot.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.tliasmanagementspringboot.common.R;
import com.itheima.tliasmanagementspringboot.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录校验拦截器
 */
@Component
@Slf4j
public class LoginCheckInterceptorBackup implements HandlerInterceptor {
    //目标资源方法执行前执行,返回true: 放行, false: 不放行

    /**
     * 功能: 目标资源方法(因为是Interceptor属于SpringBoot下的,所以资源方法一般指的是Controller层)执行前执行。 返回true：放行    返回false：不放行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        System.out.println("preHandle(拦截器执行了) .... ");
        //1.获取请求头token
        String token = request.getHeader("token");
        //2.解析头中的JWT令牌字符串
        try {
            JwtUtils.parseJWT(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();//打印到控制台
            log.error("用户未登录");
            R error = R.error("NOT_LOGIN");//和前端约定好的返回的msg的信息,
            String json = new ObjectMapper().writeValueAsString(error);//自带的
            String json1 = JSON.toJSONString(error); //fastjson的API和上面的额二选一就行
            //解决乱码问题->指定内容类型和字符集
            response.setContentType("application/json;charset=uft-8");
            response.getWriter().write(json1);//响应给前端
            return false;//不放行(相当于非法令牌)
        }
    }

    /**
     * 功能: 目标资源方法执行后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle(SpringBoot拦截器放行且资源方法执行后执行,暂时用不上)....");
    }

    /**
     * 功能: 视图渲染完毕后执行，最后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion(视图渲染完毕后执行，最后执行,暂时用不上)...");
    }
}
